<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/sj-request'

// 角色列表数据
const roleList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 加载状态
const loading = ref(false)
// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框显示控制
const dialogVisible = ref(false)
const dialogTitle = ref('添加角色')

// 表单数据
const roleForm = reactive({
  id: null,
  name: '',
  description: ''
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }
  ]
}

// 表单引用
const formRef = ref(null)

// 获取角色列表
const fetchRoles = async () => {
  loading.value = true
  try {
    const res = await request({
      url: '/role/page',
      method: 'get',
      params: {
        page: pagination.value.currentPage,
        size: pagination.value.pageSize,
        keyword: searchKeyword.value
      }
    })
    
    if (res.code === 200) {
      roleList.value = res.data.records.map((role, index) => ({
        ...role,
        order: index + 1
      }))
      pagination.value.total = res.data.total
    } else {
      ElMessage.error(res.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  fetchRoles()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  fetchRoles()
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchRoles()
}

// 处理重置筛选条件
const handleReset = () => {
  searchKeyword.value = ''
  pagination.value.currentPage = 1
  fetchRoles()
}

// 打开添加角色对话框
const handleAdd = () => {
  dialogTitle.value = '添加角色'
  resetForm()
  dialogVisible.value = true
}

// 打开编辑角色对话框
const handleEdit = (row) => {
  // 禁止编辑管理员角色
  if (row.name === '管理员') {
    ElMessage.warning('不能编辑管理员角色')
    return
  }
  
  dialogTitle.value = '编辑角色'
  resetForm()
  
  // 填充表单数据
  roleForm.id = row.id
  roleForm.name = row.name
  roleForm.description = row.description
  
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  roleForm.id = null
  roleForm.name = ''
  roleForm.description = ''
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const isEdit = roleForm.id !== null
        const url = isEdit ? '/role' : '/role'
        const method = isEdit ? 'put' : 'post'
        const data = isEdit ? {
          id: roleForm.id,
          name: roleForm.name,
          description: roleForm.description
        } : {
          name: roleForm.name,
          description: roleForm.description
        }
        
        const res = await request({
          url,
          method,
          data
        })
        
        if (res.code === 200) {
          ElMessage.success(isEdit ? '编辑成功' : '添加成功')
          dialogVisible.value = false
          fetchRoles()
        } else {
          ElMessage.error(res.message || (isEdit ? '编辑失败' : '添加失败'))
        }
      } catch (error) {
        console.error(isEdit ? '编辑角色失败:' : '添加角色失败:', error)
        ElMessage.error(isEdit ? '编辑失败' : '添加失败')
      }
    }
  })
}

// 删除角色
const handleDelete = (id, name) => {
  // 禁止删除管理员角色
  if (name === '管理员') {
    ElMessage.warning('不能删除管理员角色')
    return
  }
  
  ElMessageBox.confirm('确定要删除该角色吗？删除后不可恢复！', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request({
        url: `/role/${id}`,
        method: 'delete'
      })
      
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchRoles()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除角色失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRoles()
})
</script>

<template>
  <div class="role-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchKeyword"
            placeholder="角色名称/描述"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 角色列表 -->
    <el-card class="list-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>角色列表</span>
          <el-button type="primary" @click="handleAdd">新增角色</el-button>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="roleList"
        border
        style="width: 100%"
      >
        <el-table-column prop="order" label="顺序" width="80" />
        <el-table-column prop="name" label="角色名称" width="120" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{row}">
            <el-button 
              link 
              type="primary" 
              size="small"
              @click="handleEdit(row)"
              :disabled="row.name === '管理员'"
            >
              编辑
            </el-button>
            <el-button 
              link 
              type="danger" 
              size="small" 
              @click="handleDelete(row.id, row.name)"
              :disabled="row.name === '管理员'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="roleForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.role-container {
  padding: 20px 0;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>